--[[ v1:
function producer()
	return io.read()
end

function consume(msg)
	print('receive msg : ', msg)
end

while true do
	local msg = producer()
	consume(msg)
end
]]

--[[ v2:等待消息过来
    coConsume = coroutine.create(
	function ()
		while true do
			local stutas, msg = coroutine.resume(coProducer)
			print('receive msg : ', msg)
		end
	end
)


coProducer = coroutine.create(
	function ()
		while true do
			local msg = io.read()
			coroutine.yield(msg)
		end
	end
)

coroutine.resume(coConsume)
]]

--[[v:让消费者通知生产者收到了多少字节消息
    coConsume = coroutine.create(
	function ()
		while true do
			local stutas, msg = coroutine.resume(coProducer)
			print('receive msg : ', msg)
			coroutine.resume(coProducer, string.len(msg))
		end
	end
)


coProducer = coroutine.create(
	function ()
		while true do
			local msg = io.read()
			local len = coroutine.yield(msg)
			print('he tell me he has recved data len is ', len)
			coroutine.yield()
		end
	end
)

coroutine.resume(coConsume)
]]

--[[--将收到的消息过滤,或者说再次打包,比如在尾部增加长度字符串
    coConsume = coroutine.create(
	function ()
		while true do
			local stutas, msg = coroutine.resume(coFilter)
			print('receive msg : ', msg)
		end
	end
)

coFilter = coroutine.create(
	function ()
		while true do
			local _, msg = coroutine.resume(coProducer)
			msg = msg..': '..string.len(msg) --这里做消息的处理
			coroutine.yield(msg)
		end
	end
)


coProducer = coroutine.create(
	function ()
		while true do
			local msg = io.read()
			coroutine.yield(msg)
		end
	end
)

coroutine.resume(coConsume)
]]

local coroutine = coroutine
coConsume = coroutine.create(
	function (filter, producer)
		while true do
			local stutas, msg = coroutine.resume(filter, producer)
			print('receive msg : ', msg)
		end
	end
)

coFilter = coroutine.create(
	function (producer)
		while true do
			local _, msg = coroutine.resume(producer)
			msg = msg..': '..string.len(msg)
			coroutine.yield(msg) --封装消息后yield返回
		end
	end
)

coProducer = coroutine.create(
	function ()
		while true do
			local msg = io.read()
			coroutine.yield(msg)
		end
	end
)
--通过回调的方式执行
coroutine.resume(coConsume, coFilter, coProducer)